/**
 * edgrid - jQuery EasyUI
 * 
 * Dependencies:
 *   datagrid
 *   messager
 * 
 */
(function($){
	function buildGrid(target){
		var opts = $(target).data('edgrid').options;
		//创建查询框
		if(opts.showToolbar && opts.querybox && opts.barBtns.query){
			opts.queryContainer = $(opts.querybox).window({
				noheader:true,
				closed:true
			});
		}
		//创建帮助框
		if(opts.showToolbar && opts.helpText && opts.barBtns.help){
			opts.helpContainer=	$("<div style='padding:5px'></div>").html(opts.helpText).appendTo('body');
			opts.helpContainer.window({
				noheader:true,
				closed:true
			});
		}
		//创建错误提示框
		if(opts.showToolbar && opts.barBtns.error){
			opts.helpContainer=	$("<div class='errorbox'></div>").appendTo('body');
			opts.helpContainer.window({
				noheader:true,
				closed:true
			});
		}
		
		
		$(target).datagrid($.extend({}, opts,{
			toolbar:createToolBar(),
			onDblClickRow:function(index,row){
				if (opts.editing){
					$.fn.edgrid.methods.edit(target,index);
					//focusEditor(field);
				}
			},
			onCancelEdit: function(index, row){
				opts.editIndex = undefined;
				if (row.isNewRecord) {
					$(this).datagrid('deleteRow', index);
				}
				if (opts.onCancelEdit) opts.onCancelEdit.call(target, index, row);
			},
			onBeforeLoad: function(param){
				$(this).datagrid('rejectChanges');
				if (opts.tree){
					var node = $(opts.tree).tree('getSelected');
					param[opts.treeParentField] = node ? node.id : undefined;
				}
				if (opts.onBeforeLoad) opts.onBeforeLoad.call(target, param);
			}
		}));
		
		//创建toolbar
		function createToolBar(){
			if(!opts.showToolbar)
				return;
			var btnArr = new Array(),
				btns = opts.barBtns;
			
			if(btns.add){
				btnArr.push({
					text:'添加',
					iconCls:'icon-add',
					handler:function(){
						$.fn.edgrid.methods.add(target);
					}
				});
				btnArr.push('-');
			}
			if(btns.edit){
				btnArr.push({
					text:'编辑',
					iconCls:'icon-edit',
					handler:function(){
						$.fn.edgrid.methods.edit(target);	
					}
				});
				btnArr.push('-');
			}
			
			if(btns.del){
				btnArr.push({
					text:'删除',
					iconCls:'icon-remove',
					handler:function(){
						$.fn.edgrid.methods.del(target);
					}
				});
				btnArr.push('-');
			}
			
			if(btns.reject){
				btnArr.push({
					text:'撤销',
					iconCls:'icon-undo',
					handler:function(){
						$.fn.edgrid.methods.reject(target);
					}
				});
				btnArr.push('-');
			}
			if(btns.save){
				btnArr.push({
					text:'保存',
					iconCls:'icon-save',
					handler:function(){
						$.fn.edgrid.methods.save(target);
					}
				});
				btnArr.push('-');
			}
			if(btns.query){
				btnArr.push({
					text:'查询',
					iconCls:'icon-search',
					handler:function(e){
						$.fn.edgrid.methods.query(e,target);
					}
				});
				btnArr.push('-');
			}
			//附属按钮
			if(opts.extBtn && opts.extBtn.length>0){
				btnArr = btnArr.concat(opts.extBtn);
				btnArr.push('-');
			}
			if(btns.error){
				btnArr.push({
					iconCls:'icon-error',
					disabled:true,
					handler:function(){
						$.fn.edgrid.methods.error(target);
					}
				});
				btnArr.push('-');
			}
			if(btns.help){	
				btnArr.push({
					iconCls:'icon-help',
					handler:function(e){
						$.fn.edgrid.methods.help(e,target);
					}
				});
				btnArr.push('-');
			}
			
			return btnArr;
		}
	}
	
	$.fn.edgrid = function(options, param){
		if (typeof options == 'string'){
			var method = $.fn.edgrid.methods[options];
			if (method){
				return method(this, param);
			} else {
				return this.datagrid(options, param);
			}
		}else{
			options = options || {};
			var state = $(this).data('edgrid');
			if (state){
				$.extend(state.options, options);
			} else {
				$(this).data('edgrid', {
					options: $.extend({}, $.fn.edgrid.defaults, options)
				});
			}
			buildGrid(this);
		}
	};
	
	$.fn.edgrid.methods = {
		options: function(target){
			var dg = $(target).data('edgrid');
			if(dg)
				return dg.options;
		},
		enableEditing: function(target){
			var opts = this.options(target);
			opts.editing = true;
		},
		disableEditing: function(jq){
			var opts = this.options(target);
			opts.editing = false;
		},
		add: function(target){
			var dg = $(target),
				opts = this.options(target);
			if(!this.checkInput(target))
				return;
			dg.datagrid('insertRow', {index:0,row:{}});
			dg.datagrid('clearSelections');
			opts.editIndex=0;
			dg.datagrid('beginEdit', 0);
			dg.datagrid('selectRow', 0);
		},
		edit: function(target, index){
			var dg = $(target),
				opts = this.options(target);
			var editIndex = opts.editIndex;
			if(!index){
				var row = dg.datagrid('getSelected');
				if(row){
					index = dg.datagrid('getRowIndex',row);	
				}
			}
			if(!index){
				$.messager.alert(opts.messages.tip,opts.messages.needRow);
				return;
			}
			if (editIndex != index){
				if (dg.datagrid('validateRow', editIndex)){
					dg.datagrid('endEdit', editIndex);
					dg.datagrid('beginEdit', index);
					opts.editIndex = index;
				} 
			}
		},
		del: function(target){
			var dg = $(target),
				opts = this.options(target);
			var rows = dg.datagrid('getSelections');
			if (!rows || rows.length==0){
				$.messager.alert(opts.messages.tip,opts.messages.needRow);
				return;
			}
			$.messager.confirm(opts.messages.confirm,opts.messages.confirmDel,function(r){
				if (r){
					for(var i=0,len=rows.length;i<len;i++){
						var index = dg.datagrid('getRowIndex',rows[i]);
						dg.datagrid('cancelEdit', index);
						dg.datagrid('deleteRow', index);
					}
				}
			});
		},
		reject:function(target){
			var dg = $(target),
				opts = this.options(target);
			$.messager.confirm(opts.messages.confirm,opts.messages.confirmReject,function(r){
				if(r){
					dg.datagrid('rejectChanges');	
				}
			});
		},
		save: function(target){
			var opts = this.options(target),
				me = this,
				datas={};
			
			if(!this.checkInput(target))
				return;
				
			var rows1 = $(target).datagrid('getChanges','inserted'),
				rows2 = $(target).datagrid('getChanges','updated'),
				rows3 = $(target).datagrid('getChanges','deleted');
			if(rows1.length>0){
				//添加default value
				if(opts.defaultValues){
					$(rows1).each(function(o){
						for(var i in opts.defaultValues){
							$(o).data(i,opts.defaultValues[i]);
						}
					});
				}
				datas.adds=rows1;
			}
			if(rows2.length>0){
				datas.edits=rows2;
			}
			if(rows3.length>0)
				datas.deletes=rows3;
			if(datas.adds || datas.edits || datas.deletes){
				//进度
				$.messager.progress({
					title:opts.messages.save,
					msg:opts.messages.progress
				});
				$.getJSON(opts.urls.batchSave,{datas:JSON.stringify(datas)},function(r){
					//关闭保存
					$.messager.progress('close');
					if(r.success){
						$.messager.alert(opts.messages.tip,opts.messages.saveSuccess);
						$(target).datagrid('accecptChanges');
					}else{
						console.log($(target).datagrid('options').toolbar);
						me.handleErr(target,r.result);
					}
				});
			}
		},
		query:function(e,target){
			var opts = this.options(target);
			
			if(opts.queryContainer){
				opts.queryContainer.window('move',{left:e.clientX-100,top:e.clientY+20});			
				if(opts.queryContainer.window('options').closed)
					opts.queryContainer.window('open');
				else
					opts.queryContainer.window('close');
			}
			
		},
		//处理错误提示
		handleErr:function(target,data){
			
			var opts = this.options(target),
				errorMsg='<ul>',
				hasErr=false;
			if(data.msgs){
				hasErr=true;
				var columns = opts.columns;
				for(var m in data.msgs){
					for(var i=0,len=columns.length;i<len;i++){
						if(m == columns[i].field)	
							errorMsg += "<li>" + data.msgs[m] + "</li>";
							break;
					}
				}
			}else if(data.errors){
				hasErr=true;
				errorMsg += data.errors;			
			}
			errorMsg += "</ul>";
			if(!opts.errorBox){
				opts.errorBox = $("<div class='edgrid-errorbox'></div>").append($(this));
			}
			if(hasErr){
				opts.errorBox.html(errorMsg);
				opts.errorBox.window('show');
			}
		},
		help:function(e,target){
			var opts = this.options(target);
			if(opts.helpContainer){
				opts.helpContainer.window('move',{left:e.clientX-100,top:e.clientY+20});			
				if(opts.helpContainer.window('options').closed)
					opts.helpContainer.window('open');
				else
					opts.helpContainer.window('close');
			}
		},
		checkInput:function(target){
			var opts = this.options(target);
			if (opts.editIndex >= 0){
				var dg = target;
				if (!dg.datagrid('validateRow', opts.editIndex)){
					dg.datagrid('selectRow', opts.editIndex);
					$.messager.alert({
						title: opts.messages.tip,
						msg: opts.messages.input
					});
					return false;
				}
				dg.datagrid('endEdit', opts.editIndex);
			}
			return true;
		}
	};
	
	$.fn.edgrid.defaults = $.extend({}, $.fn.datagrid.defaults, {
		editing: true,
		defaultValues:null,   //新增时默认记录参数值
		editIndex:-1,		  //编辑行
		messages:{
			tip:'提示',
			warning:'警告',
			error:'错误',
			save:'保存',
			confirm:'确认',
			needRow:'请选择行',
			input:'请检查输入项',
			confirmDel:'确定要删除选中记录?',
			confirmReject:'确定撤销已执行操作?',
			saveSuccess:'保存成功',
			saveFailed:'保存失败',
			progress:'保存中...'
		},
		/**
		 * 操作url
		 */
		urls:{
			add:null,
			edit:null,
			del:null,
			batchSave:null
		},
		showToolbar:true,
		//工具栏按钮
		barBtns:{   
			add:true,       //添加按钮
			edit:true,      //编辑按钮
			del:true,		//删除按钮
			reject:true,	//撤销修改
			save:true,		//保存按钮
			query:true,	 	//条件查询
			error:true,		//错误按钮
			help:true		//帮组按钮
		},
		helpText:"<ul>" +
					"<li>添加：添加一条记录</li>" +
					"<li>编辑：双击记录进行编辑</li>" +
					"<li>删除：删除选中一条或多条记录</li>" +
					"<li>撤销：可点击撤销按钮撤销之前的操作</li>" +
					"<li>保存：所有的操作点击保存将提交到服务器,保存成功后不可撤销</li>" +
				 "</ul>"
		,
		//附加工具栏
		extBtn:[]
	});
})(jQuery);